<?php
namespace Admin\Controller;
use Think\Controller;

/**
 * Class KVController
 * @package Admin\Controller
 * Key_to_value控制器
 */
class KVController extends Controller {
    public $table = 'KeyToValue';
    private $successUrl = '../KeyToValue/index';
    private $errorUrl = '../KeyToValue/index';
    private  $uniqueIndex = 'key';

    public function index(){
        $this->display();
    }

    public function add(){
        //说明是增加表单
        if(IS_POST){
            $obj = D($this->table);
            $obj->addObj($_POST, $this->uniqueIndex);
            $this->success(LANG('save_success'));
        }else{
            $this->display("add");
        }
    }

    /**
     * 编辑
     */
    public function edit(){
        $obj = D($this->table);
        if(IS_GET){
            $Id = I("get.id");
            $obj = $obj->queryObj($Id, 'id');
            $this->assign('obj',$obj);
            $this->display("edit");
        }else{
            $obj = $obj->updateObj($_POST);
            $this->success(LANG('save_success'));
        }
    }

    /**
     * 获得的全部
     */
    public function getAll(){
        $model = D($this->table);
        $list = $model->getAll();
        foreach($list as $k => $v){
            switch($list[$k]['input_type']){
                case 'input':
                    $list[$k]['input_type'] = '文字';
                    break;
                case 'textarea':
                    $list[$k]['input_type'] = '文字域';
                    break;
                case 'image':
                    $list[$k]['input_type'] = '图片';
                    break;
                case 'file':
                    $list[$k]['input_type'] = '文件';
                    break;
            }
        }
        echo json_encode($list);
    }

    public function deleteArray(){
        $ids = I("post.ids");
        $model = D($this->table);
        if($model->deleteArray($ids)){
            echo '[{"status":1}]';
        }else{
            echo '[{"status":0}]';
        }
    }

    public function uploadify(){
        if (!empty($_FILES)) {
            import("@.Think.UploadFile");
            $upload = new \Think\Upload();
            $upload->rootPath  = C('UPLOAD_ROOT_PATH');
            $upload->savePath = C('UPLOAD_SAVE_PATH');
            $upload->autoSub = false;
            $upload->saveRule = uniqid; //上传规则
            $info = $upload->upload();
            if(!$info){
                echo $this->error($upload->getError());//获取失败信息
            } else {
                //成功
                $fileArray = "";
                foreach ($info as $file) {
                    $fileArray = '/upload_src/' . $file['savepath'] . $file['savename'];
                }
                echo trim($fileArray);
            }
        }
    }
}